package yiranyousheng.com.alarm_r;

import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.PowerManager;
import android.support.v7.app.ActionBarActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;

import java.util.Calendar;
import java.util.HashSet;
import java.util.Set;


public class MainActivity extends ActionBarActivity {

    private String mUrl;
    public static final  String ALARM_FLAG = "alarm_flag";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setupViews();
        initialized();
        initAlarm();
    }

    private void initAlarm() {
        Intent intent   = getIntent();
        if(intent != null && ALARM_FLAG.equals(intent.getStringExtra(ALARM_FLAG))){
            //存在闹钟
            play();
            initNextALarm();//初始化下一个闹钟
        }
    }

    private void initNextALarm() {
        AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(getApplicationContext(), AlarmReceiver.class);
        int requestCode = 0;
        PendingIntent pendIntent = PendingIntent.getBroadcast(getApplicationContext(),
                requestCode, intent,0);

        Set<String> repeats = getSharedPreferences("settings",MODE_PRIVATE).getStringSet(AlarmActivity.ALARM_REPEAT, new HashSet<String>());
        if(repeats.size()>1){
            Calendar cal = Calendar.getInstance();
            int  week =   cal.get(Calendar.DAY_OF_WEEK);
            System.out.println("week = " + week);    //周日：1
            int last =10;
            for (String sid : repeats) {
                if (!TextUtils.isEmpty(sid)) {
                    int interval = Integer.parseInt(sid) - week;
                    interval = min(last, interval > 0 ? interval : 7 - interval);
                    last = interval;
                }
            }
            System.out.println("last ="+last);
            cal.add(Calendar.DATE, last);
            getSharedPreferences("settings",MODE_PRIVATE).edit().putLong(AlarmActivity.ALARM_TIME,cal.getTimeInMillis()).commit();
            alarmMgr.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendIntent);
        }else{
            alarmMgr.cancel(pendIntent);
        }

    }

    private int min(int interval, int i) {
        return interval<i?interval:i;
    }

    private void play() {
        String pickUri = getSharedPreferences("settings",MODE_PRIVATE).getString(AlarmActivity.ALARM_URI,"");
        if(TextUtils.isEmpty(pickUri)) return;
        final MediaPlayer  player= new MediaPlayer();
        try{
            player.setDataSource(this, Uri.parse(pickUri));
        }catch(Exception e){
            e.printStackTrace();
        }
        final AudioManager audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
        if(audioManager.getStreamVolume(AudioManager.STREAM_ALARM)!=0){
            player.setAudioStreamType(AudioManager.STREAM_ALARM);
            player.setLooping(true);
            try {
                player.prepare();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            player.start();
        }else{
            Toast.makeText(this,"当前闹钟音量静音，请重新设置",Toast.LENGTH_SHORT).show();
        }

        new AlertDialog.Builder(this)
                .setIcon(R.drawable.msp_edit_warning)
                .setTitle("提示")
                .setMessage("已经完成闹钟，点击以关闭音乐")
                .setPositiveButton("关闭", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        stopPlay(player);
                    }
                })
                .show();
    }
    private void stopPlay(MediaPlayer player){
        if (player==null) return;;
        player.stop();
        player.release();
        player = null;
    }

    protected void setupViews() {
        findById();
        initView();
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish();
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    protected void initialized() {
        setListener();
    }


    /**
     * 进度条
     */
    private ProgressBar progressBar;
    /**
     * 工具栏顶部横线
     */
    private View toolbarline;

    /**
     * 是否点击刷新按钮
     */
    private RelativeLayout webviewBottom;
    /**
     * 网页
     */
    private WebView webView;
    private WebSettings settings;


    /**
     * 初始化界面
     */
    private void initView() {
        //webView.loadUrl("http://www.baidu.com");
        mUrl = "http://cj.wxhttx.com/v-U6056K7X49?eqrcode=1&from=singlemessage&isappinstalled=0";
        System.out.println(mUrl);
        webView.loadUrl(mUrl);

    }


    /**
     * 设置监听
     */
    private void setListener() {

    }


    /**
     * 初始化ui
     */
    @SuppressLint({"JavascriptInterface", "SetJavaScriptEnabled"})
    private void findById() {

        toolbarline = findViewById(R.id.toolbarline);
        webviewBottom = (RelativeLayout) findViewById(R.id.webviewBottom);
        progressBar = (ProgressBar) findViewById(R.id.progressbar);
        webView = (WebView) findViewById(R.id.webview);

        settings = webView.getSettings();
        // 设置WebView属性，能够执行Javascript脚本
        settings.setJavaScriptEnabled(true);
        // js与android调用接口
        webView.addJavascriptInterface(new MyJavascriptInterface(), "android");
        // 设置Web视图
        webView.setWebViewClient(new MyWebViewClient());
        // 处理Javascript的对话框、网站图标、网站title、加载进度等
        webView.setWebChromeClient(new MyWebChromeClient());

        findViewById(R.id.fab_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println("startActivity");
                startActivity(new Intent(MainActivity.this,AlarmActivity.class));
            }
        });


    }


    class MyJavascriptInterface {
        public MyJavascriptInterface() {
        }

    }


    class MyWebChromeClient extends WebChromeClient {


        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
        }


        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                progressBar.setProgress(newProgress);
                progressBar.setVisibility(View.GONE);


            } else {
                if (progressBar.getVisibility() == View.GONE)
                    progressBar.setVisibility(View.VISIBLE);
                progressBar.setProgress(newProgress);
            }


            super.onProgressChanged(view, newProgress);
        }
    }


    class MyWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }


    private long mExitTime;

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        //onKeyDown 与parentActivity 的dispatchKeyEvent 冲突
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP && webView.canGoBack()) {
            webView.goBack();
            return true;
        } else {
            return super.dispatchKeyEvent(event);
        }
    }

    @Override
    public void onBackPressed() {
        long mNowTime = System.currentTimeMillis();//获取第一次按键时间
        if ((mNowTime - mExitTime) > 2000) {//比较两次按键时间差
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            mExitTime = mNowTime;
        } else {//退出程序
            this.finish();
            System.exit(0);
        }
    }

    //@Override
    //public void onBackPressed() {
    //	showShortToast("onBackPressed =="+webView.canGoBack());
    //	if (webView.canGoBack()) {
    //		btFlag = "back";
    //		webView.goBack();
    //	}else {
    //		finish();
    //	}
    //}


    @Override
    protected void onDestroy() {
        super.onDestroy();
        webView.clearHistory();
    }


    PowerManager.WakeLock mWakelock;
    @Override
    protected void onResume() {
        super.onResume();
        PowerManager pm= (PowerManager)getSystemService(Context.POWER_SERVICE);
        mWakelock  = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP |PowerManager.SCREEN_DIM_WAKE_LOCK, "SimpleTimer");
        mWakelock.acquire();


    }

    @Override
    protected void onStop() {
        super.onStop();
        mWakelock.release();
        mWakelock=null;
    }
}
